'use strict';

define([
  'angular',
  'angularAMD',
  'angular-cookies'
], function(ng, angularAMD) {

  angularAMD.controller('productsCtrl', ['$scope', '$http', '$location',
    function($scope, $http, $location) {
      var searchObj = $location.search();
      var limit=10000,page=1;
      // var page=1;
      var hasMore = true;
      var adding = false;
      $scope.searchParams = searchObj;
      searchObj.limit = limit;
      searchObj.page = page;
      loadProducts(searchObj);

      $scope.sort = function(key){
        page = 1;
        $scope.searchParams.page = page;
        $scope.searchParams.sort = key;
        $scope.searchParams.order = $scope.searchParams.order && $scope.searchParams.order == "asc" ? "desc" : "asc";
        loadProducts($scope.searchParams);
      }

      if(searchObj.category){
        $http.get("index.php?route=feed/rest_api/categories&id="+searchObj.category).then(
          function(result) {
            if (result.data.success) {
              $scope.filterGroups = result.data.data.filters.filter_groups;
            }
          }
        )
      }else{
        $scope.filterGroups = [];
      }

      $scope.filter = function(){
        var filterIds = "";
        angular.forEach($scope.filterGroups,function(filterGroup,index){
          if(filterGroup.currOption && filterGroup.currOption.filter_id){
            filterIds += filterGroup.currOption.filter_id + ",";
          }
        })
        if(filterIds.charAt(filterIds.length-1) == ","){
          filterIds = filterIds.substring(0,filterIds.length-1);
        }
        page = 1;
        var searchParams = {category : searchObj.category, page : page, limit : limit};
        if(filterIds && filterIds.length>0){
          searchParams.filters = filterIds;
          $scope.filterIds = filterIds;
          $scope.filtering = true;
        }else{
          $scope.filtering = false;
        }
        loadProducts(searchParams);
      }

      $scope.selectOption = function(filterGroup,filterOption){
        if(filterGroup.currOption && filterGroup.currOption.filter_id == filterOption.filter_id){
          filterGroup.currOption = {};
        }else{
          filterGroup.currOption = filterOption;
        }
      }

      $scope.updateQuantity = function(type,product){
        if(!product.selectQuantity){
          product.selectQuantity = 1;
        }
        if(type == "reduce"){
          if(product.selectQuantity > 1){
            product.selectQuantity--;
          }
        }else if(type == "add"){
          product.selectQuantity++;
        }
      }

      var $w = $(window);
      $w.bind("scroll", function(){
        if($("#LoadingPlace").length>0 && $w.scrollTop()+$w.height() > $("#LoadingPlace").offset().top && hasMore){
          var params = ng.copy($scope.searchParams);
          if($scope.filterIds){
            params.filter = $scope.filterIds;
          }
          if(page == 1){
            page = 2;
          }
          params.page = page;
          loadMoreProducts(params); 
        }
      });

      $scope.addToCart = function(product){
        //if(product.options && product.options.length>0){
          //BHZ.MessageDialog.show("请前往商品详情页选择规格尺寸！","知道了");
          //return;
        //}
        //if(parseInt(product.selectQuantity) < product.minimum){
          //BHZ.MessageDialog.show("商品购买数量不能小于起批个数！","知道了");
          //return;
        //}
		//if(parseInt($scope.selection.quantity) >= $scope.product.minimum && parseInt($scope.selection.quantity) % $scope.product.minimum != 0){
          //BHZ.MessageDialog.show("商品购买数量必须是起批个数的倍数！","知道了");
          //return;
        //}
        if(adding){
          console.log('waiting for last adding');
          return;
        }
        var option = {};
        if(product.options.length > 1){

          BHZ.MessageBox.show("此商品需在进入商品详情页面后再选择下单。");
          return;

        }else if(product.options.length == 1){
          if(!product.options[0].flag){

            BHZ.MessageBox.show("此商品需在进入商品详情页面后再填写下单。");
            return;

          }else if(product.options[0].option_value.length > 1){

            BHZ.MessageBox.show("此商品需在进入商品详情页面后再选择下单。");
            return;

          }
        }

        if(product.options && product.options.length>0){
          option[product.options[0].product_option_id] = product.options[0].option_value[0].product_option_value_id;
        }

        var params = {
          "product_id":product.id,
	      "show_cart":product.show_cart,
          "quantity":product.minimum,
          "option":option
        }
        adding = true;
        $http.post("index.php?route=rest/cart/cart",params).then(
          function(result) {
            adding = false;
            if (result.data.success) {
              BHZ.MessageBox.show("加入进货单成功！");
            }else{
              BHZ.MessageBox.show("加入进货单失败");
            }
          },function(error){
            adding = false;
          }
        )
      }

      function loadMoreProducts(searchParams) {
        if($scope.loading){
          return;
        }
        var baseUrl = "index.php?route=feed/rest_api/products&simple=1";
        for(var key in searchParams){
          if(searchParams[key]){
            baseUrl += "&"+key+"="+searchParams[key];
          }
        }
        $scope.loading = true;
        $http.get(baseUrl,{header : {'Content-Type' : 'application/json; charset=UTF-8'}}).then(
            function(result) {
              $scope.loading = false;
              page++;
              if (result.data.success) {
                if(result.data.data.length == 0){
                  hasMore = false;
                  $scope.withoutMore = true;
                  return;
                }
                if($scope.products && $scope.products.length>0){
                  angular.forEach(result.data.data,function(productItem){
                    productItem.selectQuantity = 1;
                    $scope.products.push(productItem);
                  })
                }else{
                  $scope.products = result.data.data;
                  angular.forEach($scope.products,function(productItem){
                    productItem.selectQuantity = 1;
                  })
                  if($scope.products.length == 0 || $scope.products.length<limit){
                    $scope.withoutMore = true;
                  }
                }
              }else{
                $scope.products = [];
                $scope.withoutMore = true;
              }
            },function(error){
              $scope.loading = false;
            }
          )
      }

      function loadProducts(searchParams) {
        if($scope.loading){
          return;
        }
        var baseUrl = "index.php?route=feed/rest_api/products&simple=1";
        for(var key in searchParams){
          if(searchParams[key]){
            baseUrl += "&"+key+"="+searchParams[key];
          }
        }
        $scope.loading = true;
        $http.get(baseUrl,{header : {'Content-Type' : 'application/json; charset=UTF-8'}}).then(
            function(result) {
              $scope.loading = false;
              if (result.data.success) {
				console.log(result.data);
                $scope.products = result.data.data;
				
				if(result.data.correct){
					var a = result.data.correct;
					var b = result.data.expand;
					$scope.helps = $.unique(a.concat(b).sort());
				}

              }else{
                $scope.products = [];
              }
              if($scope.products.length == 0 || $scope.products.length<limit){
                $scope.withoutMore = true;
                hasMore = false;
              }
            },function(error){
              $scope.loading = false;
            }
          )
      }
    }
  ]);

  angularAMD.controller('productCtrl', ['$routeParams', '$scope', '$sce', '$http', '$location', '$timeout', '$window',
    function($routeParams, $scope, $sce, $http, $location, $timeout, $window) {
      var productImagesSlider,initSwiperFlag;
      var productId = $routeParams.product_id;
      var adding = false;
      if(!productId){
        alert("缺少商品ID!");
        return;
      }

      //将本页从头开始
      $window.scrollTo(0,0);

      $scope.selection = {
        tab:1,
        secondTab:1,
        quantity:1,
        currViewIndex:0
      }

      $http.get("index.php?route=feed/rest_api/products&id="+productId).then(
          function(result) {
            if (result.data.success) {
              var product = result.data.data;
              product.description = $sce.trustAsHtml(product.description);
              var attrArgs = [];
              if(product.attribute_groups && product.attribute_groups.length > 0){
                angular.forEach(product.attribute_groups,function(attr_group,index){
                  if(attr_group.attribute){
                    angular.forEach(attr_group.attribute,function(attr_item,index){
                      attrArgs.push(attr_item);
                    })
                  }
                })
                product.attr_args = attrArgs;
              }
              if(product.images){
                product.images.splice(0,0,product.image);
              }
              if(product.reviews && product.reviews.reviews){
                angular.forEach(product.reviews.reviews,function(review){
                  if(review.author.length>2){
                    review.author = review.author.charAt(0)+"***"+review.author.charAt(review.author.length-1);
                  }
                  review.avatar = review.avatar || "catalog/view/theme/bhz/m/images/default-avarta.png";
                })
              }
              $scope.product = product;
              $scope.selection.quantity = $scope.product.minimum;
              if(product.options.length>0){
                $scope.product_option_id = product.options[0].product_option_id;
                if(product.options[0].option_value && product.options[0].option_value.length>0){
                  $scope.selectOption(product.options[0],product.options[0].option_value[0]);
                  $scope.selection.quantity = $scope.product.minimum;
                }
              }
            }
          }
      )

	/*组合商品快捷添加进货单*/
	$scope.fastAdd = function(data){

		var id = data['id'];
		data['submitqty'] = $("input[name='submit-quantity"+id+"']").val();

		$scope.addSingleCart(1,data);

	}
	/*组合商品快捷添加进货单*/
	  
	/*组合商品单独添加进货单*/
	$scope.addSingleCart = function(type,product){

		var option = {};
        if(product.options && product.options.length>0){
          option[product.options[0].product_option_id] = product.options[0].product_option_value[0].product_option_value_id;
        }

		var params = {
			"product_id":product.id,
		    "show_cart":product.show_cart,
			"quantity":product.submitqty,
			"option":option
		}

        $http.post("index.php?route=rest/cart/cart",params).then(
			function(result) {
				if(result.data.success){
					if(type == 1){
						BHZ.MessageBox.show("加入进货单成功！");
					}
				}
				else{
					BHZ.MessageBox.show("加入进货单失败");
				}
			}
		)

	}
	/*组合商品单独添加进货单*/

	/*组合商品批量添加进货单*/
	$scope.singleToCart = function(){

		var checkAll = true;
		var noChangeQty = true;
		var gproduct = [];
		$(".check-box").each(function(){	

			if(this.checked == false){
				checkAll = false;
			}
			else{
				
				if($(this).parent().find("input[name='gp_is_single']").val()==1){

					var id = $(this).parent().find("input[name='gp_id']").val();
					var gps = $scope.product.group_products;
					
					for(var i = 0;i<gps.length;i++){

						if(id == gps[i]['id']){
							
							gps[i]['submitqty'] = $("input[name='submit-quantity"+id+"']").val();

							//判断数量是否和套装数量不同
							if(gps[i]['submitqty'] != gps[i]['qty']){
								noChangeQty = false;
							}

							gproduct.push(gps[i]);

						}
						
					}

				}

			}

		});

		if(checkAll == true && noChangeQty == true){

			$scope.addToCart();

		}
		else{

			if(gproduct.length==0)
			{
				BHZ.MessageBox.show("请至少选择一件可单卖商品");
			}
		
			for(var i=0;i<gproduct.length;i++){
			
				$scope.addSingleCart(1,gproduct[i]);

			};

		}

	}
	/*组合商品批量添加进货单*/

	/*批量购买*/
	$scope.batchBuy = function(){
		
		var checkAll = true;
		var noChangeQty = true;
		var gproduct = [];
		$(".check-box").each(function(){	

			if(this.checked == false){
				checkAll = false;
			}
			else{

				if($(this).parent().find("input[name='gp_is_single']").val()==1){

					var id = $(this).parent().find("input[name='gp_id']").val();
					var gps = $scope.product.group_products;
					
					for(var i = 0;i<gps.length;i++){

						if(id == gps[i]['id']){
							
							gps[i]['submitqty'] = $("input[name='submit-quantity"+id+"']").val();

							//判断数量是否和套装数量不同
							if(gps[i]['submitqty'] != gps[i]['qty']){
								noChangeQty = false;
							}

							gproduct.push(gps[i]);

						}
						
					}

				}

			}

		});

		if(checkAll == true && noChangeQty == true){

			$scope.gotoBuy();

		}
		else{
			
			if(gproduct.length==0)
			{
				BHZ.MessageBox.show("请至少选择一件可单卖商品");
			}
		
			for(var i=0;i<gproduct.length;i++){
			
				$scope.addSingleCart(2,gproduct[i]);

			};

			$location.url("/cart");

		}

	}
	/*批量购买*/

      $scope.addTowishlist = function(){
        if($scope.product.is_in_wishlist){
          $http.delete('index.php?route=rest/wishlist/wishlist&id=' + productId).then(function(result){
            if(result.data.success){
              $scope.product.is_in_wishlist =  false;
              BHZ.MessageBox.show("取消关注成功！");
            }
          })
        }else{
          $http.post('index.php?route=rest/wishlist/wishlist&id=' + productId).then(function(result){
            if(result.data.success){
              $scope.product.is_in_wishlist =  true;
              BHZ.MessageBox.show("加入收藏成功");
            }
          })
        }
      }

      $scope.addToCart = function() {
        if(($scope.product.options && $scope.product.options.length>0)){
          if(!$scope.product.options[0].selectOptionValue){
            BHZ.MessageDialog.show("请选择规格尺寸！","知道了");
            return;
          }
        }
        if(parseInt($scope.selection.quantity) < $scope.product.minimum){
          BHZ.MessageDialog.show("商品购买数量不能小于起批个数！","知道了");
          return;
        }
		if(parseInt($scope.selection.quantity) >= $scope.product.minimum && parseInt($scope.selection.quantity) % $scope.product.minimum != 0){
          BHZ.MessageDialog.show("商品购买数量必须是起批个数的倍数！","知道了");
          return;
        }
		
		if($scope.product.is_single==0){
			BHZ.MessageDialog.show("B类商品不能单买");
		}
		if($scope.product.show_cart==2){
			BHZ.MessageDialog.show("此商品正在备货中");
		}

        if(adding){
          console.log('waiting for last adding');
          return;
        }
        var option = {};
        if($scope.product.options && $scope.product.options.length>0){
          option[$scope.product.options[0].product_option_id] = $scope.product.options[0].selectOptionValue;
        }
        var params = {
          "product_id":productId,
		  "show_cart":$scope.product.show_cart,
          "quantity":$scope.selection.quantity,
          "option":option
        }
        adding = true;
        $http.post("index.php?route=rest/cart/cart",params).then(
          function(result) {
            adding = false;
            if (result.data.success) {
              BHZ.MessageBox.show("加入进货单成功！");
            }else{
              BHZ.MessageBox.show("加入进货单失败");
            }
          },function(error){
            adding = false;
          }
        )
      }

      $scope.gotoBuy = function(){
        if(($scope.product.options && $scope.product.options.length>0)){
          if(!$scope.product.options[0].selectOptionValue){
            BHZ.MessageDialog.show("请选择规格尺寸！","知道了");
            return;
          }
        }
        if(parseInt($scope.selection.quantity) < $scope.product.minimum){
          BHZ.MessageDialog.show("商品购买数量不能小于起批个数！","知道了");
          return;
        }
		if(parseInt($scope.selection.quantity) >= $scope.product.minimum && parseInt($scope.selection.quantity) % $scope.product.minimum != 0){
          BHZ.MessageDialog.show("商品购买数量必须是起批个数的倍数！","知道了");
          return;
        }
		
		if($scope.product.is_single == 0){
			BHZ.MessageDialog.show("B类商品不能单买");
		}
		if($scope.product.show_cart==2){
			BHZ.MessageDialog.show("此商品正在备货中");
		}

        if(adding){
          console.log('waiting for last adding');
          return;
        }
        var option = {};
        if($scope.product.options && $scope.product.options.length>0){
          option[$scope.product.options[0].product_option_id] = $scope.product.options[0].selectOptionValue;
        }
        var params = {
          "product_id":productId,
	      "show_cart":$scope.product.show_cart,
          "quantity":$scope.selection.quantity,
          "option":option
        }
        adding = true;
        $http.post("index.php?route=rest/cart/cart",params).then(
          function(result) {
            adding = false;
            if (result.data.success) {
              $location.url("/cart");
            }else{
              BHZ.MessageDialog.show("加入进货单失败，不能立即购买","知道了");
            }
          },function(error){
            adding = false;
          }
        )
      }

      $scope.selectOption = function(option,optionValue){
        option.selectOptionValue = optionValue.product_option_value_id;
        var price = 0;
        if(optionValue.price_prefix == '+'){
          price = parseFloat($scope.product.special) + parseFloat(optionValue.price); 
        }else{
          price = parseFloat($scope.product.special) - parseFloat(optionValue.price); 
        }
        $scope.product.curr_select_price = "￥" + price.toFixed(2);
      }

      $scope.updateQuantity = function(type){
        if(!$scope.selection.quantity){
          $scope.selection.quantity = 1;
        }
        if(type == "reduce"){
          if($scope.selection.quantity >= 2*parseInt(document.getElementById("pro_batch").innerHTML)){
			if($scope.selection.quantity % parseInt(document.getElementById("pro_batch").innerHTML) == 0)
				$scope.selection.quantity=parseInt($scope.selection.quantity)-parseInt(document.getElementById("pro_batch").innerHTML);
			else
				$scope.selection.quantity=parseInt($scope.selection.quantity)-parseInt($scope.selection.quantity)%parseInt(document.getElementById("pro_batch").innerHTML);
          }else{
		    $scope.selection.quantity=document.getElementById("pro_batch").innerHTML;
		  }
        }else if(type == "add"){
          $scope.selection.quantity=parseInt($scope.selection.quantity)+parseInt(document.getElementById("pro_batch").innerHTML);
		  if($scope.selection.quantity % parseInt(document.getElementById("pro_batch").innerHTML) != 0)
			$scope.selection.quantity=parseInt($scope.selection.quantity)-parseInt($scope.selection.quantity)%parseInt(document.getElementById("pro_batch").innerHTML);
        }
      }

      $scope.initSwiper = function() {
        if(!initSwiperFlag){
          initSwiperFlag = true;
          $timeout(function() {
            productImagesSlider = new Swiper('#productSlider', {
              spaceBetween: 10,
              slidesPerView: 5,
              nextButton: '.swiper-button-next',
              prevButton: '.swiper-button-prev',
            });
          })
        }
      }

      $scope.changeViewIndex = function(key){
        $scope.selection.currViewIndex = key;
      }

      $scope.switchTab = function(tabIndex){
        $scope.selection.tab = tabIndex;
      }

      $scope.back = function(){
        $window.history.back();
      }
    }
  ]);

  angularAMD.directive('onNgRepeatEnd', function ($timeout) {
    return {
      restrict: 'A',
      link: function($scope, element, attr) {
        if ($scope.$last == true) {
          $timeout(function() {
            $scope.$eval(attr.onNgRepeatEnd);
          });
        }
      }
    };
  });

});
